<template>
    <div class="sticky-box">
        <div class="item-title title-tips">
            {{ title || $t('message.text.library') }}{{ $t('message.text.dynamicReminder') }}
            <span class="tips">{{ $t('message.text.dynamicReminderTips') }}{{ title
                || $t('message.text.library')}}{{ $t('message.text.dynamicReminderTips1') }}</span>
        </div>
        <div class="message-type-box">
            <div v-for="(item, index) in messageType" :key="index" class="message-item" :class="[!disabled && 'disabled']">
                <span @click="changeMessageStatus(item)">
                    <svg class="radio-icon">
                        <use
                            v-bind:xlink:href="`#${knowForm.readNotify == item.value ? 'keowledge-a-zu3772' : 'keowledge-a-yuanxing5biankuang'}`">
                        </use>
                    </svg>
                    <span>{{ $t(item.label) }}</span>
                </span>
            </div>
        </div>
        <template v-if="knowForm.readNotify">
            <div class="item-title">
                <span class="title">{{ title || $t('message.text.library') }}{{ $t('message.text.dynamicReminder') }}</span>
                <span class="add-auth" @click="addMessage"><i class="knowledge-iconfont keowledge-tianjia"
                        v-if="disabled"></i>{{ $t('message.text.addMessageNotice') }}</span>
            </div>
        </template>
    </div>
    <template v-if="knowForm.readNotify">
        <div class="message-lists">
            <div v-for="(item, index) in messageList" :key="index" class="message-list-item">
                <el-select v-model="item.messageType" :no-data-text="$t('message.empty.nullData')"
                    :placeholder="$t('message.placeholder.selectNotificationType')"
                    @change="changeMessageType(item, index)" :disabled="!disabled">
                    <el-option v-for="(mt) in messageTypeList" :key="mt.key" :label="$t(mt.label)"
                        :value="mt.key"></el-option>
                </el-select>
                <el-select v-model="item.operationType" :no-data-text="$t('message.empty.nullData')"
                    :placeholder="$t('message.placeholder.selectTuchEvent')" :disabled="!disabled">
                    <el-option v-for="(mTM, mTMI) in getTrigMes" :key="mTMI" :label="$t(mTM.label)"
                        :value="mTM.value"></el-option>
                </el-select>
                <el-select :no-data-text="$t('message.empty.nullData')"
                    :placeholder="$t('message.placeholder.selectMessageTemplate')" v-model="item.messageId"
                    :disabled="!disabled">
                    <el-option v-for="(tempItem, tempIndex) in getCurrentTemplateList(item.messageType)" :key="tempIndex"
                        :label="tempItem.name" :value="tempItem.id"></el-option>
                </el-select>
                <el-select :no-data-text="$t('message.empty.nullData')"
                    :placeholder="$t('message.placeholder.selectSendUser')" v-model="item.userId"
                    @change="(val) => roleChange(val, index)" :disabled="!disabled">
                    <el-option v-for="(uItem, uIndex) in roleList" :key="uIndex" :label="uItem.name"
                        :value="uItem.id"></el-option>
                </el-select>
                <div class="item-action" @click="delMessage(index)" v-if="disabled && messageList.length > 1">
                    <svg class="del-icon">
                        <use xlink:href="#keowledge-shanchuquanxianzu"></use>
                    </svg>
                </div>
            </div>
        </div>
    </template>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    getCurrentInstance,
    computed
} from 'vue'
import { getStore } from '@/utils/store'
import { messageInsideSelect, messageEmailSelect, messageSmsSelect, messageWxSelect, messageGet } from '@/api/message'
import { useRouter } from "vue-router"
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits(["changeMessageStatus"])
const props = defineProps({
    knowForm: {
        type: Object,
        default() {
            return {}
        }
    },
    title: {
        type: String,
        default: ''
    },
    disabled: {
        type: Boolean,
        default: false
    }
})
const messageType = ref([{
    label: 'message.text.notPushDynamicMessage',
    value: false
}, {
    label: 'message.text.pushDynamicMessage',
    value: true
}])
interface messageObj {
    messageType: string,
    userId: string,
    messageId: string,
    operationType: string,
    facilitator: string,
    dataAuthType: string
}
const messageList = ref<messageObj[]>([])
const messageTypeList = ref([{
    label: 'message.typeMenu.onSiteNotifi',
    value: 'INSIDE_NOTIFICATION',
    key: 'inside',
}, {
    label: 'message.typeMenu.smsNotifi',
    value: 'ALI_SMS',
    key: 'sms',
}, {
    label: 'message.typeMenu.emailNotifi',
    value: 'EMAIL',
    key: 'email',
}, {
    label: 'message.typeMenu.weChatNotifi',
    value: 'WECHAT_OFFICIAL_ACCOUNT',
    key: 'wx_template',
}])
const templateList = ref({
    'inside': null,
    'sms': null,
    'email': null,
    'wx_template': null
})
const triggerMessage = ref([{
    label: 'message.auth.libraryDel',
    value: 'library_del',
    showType: "knowledge"
}, {
    label: 'message.auth.libraryEdit',
    value: 'library_update',
    showType: "knowledge"
}, {
    label: 'message.auth.documentDel',
    value: '"document_del"'
}, {
    label: 'message.auth.documentEdit',
    value: 'document_update'
}, {
    label: 'message.auth.createDocument',
    value: 'document_add',
    showType: "knowledge"
}])
const roleList = ref([])
// 根据类型设置消息的通知类型
const getTrigMes = computed(() => {
    let arr = []
    triggerMessage.value.forEach((item) => {
        if (!item.showType || props.knowForm.type == item.showType) {
            arr.push(item)
        }
    })
    return arr
})
function init() {
    if (props.knowForm.id) {
        getAllMes()
    }
}
function getAllMes() {
    messageGet({
        businessId: props.knowForm.id
    }).then(res => {
        if (res.data.code == 0) {
            messageList.value = res.data.data
            getMessageSet()
        }
    })
}
function changeMessageStatus(item) {
    if (!props.disabled) return
    emit('changeMessageStatus', item)
    if (item.value) {
        if (messageList.value.length == 0) {
            messageList.value.push({
                messageType: '',
                userId: '',
                messageId: '',
                operationType: '',
                facilitator: '',
                dataAuthType: ''
            })
        }
    }
}
// 添加消息通知
function addMessage() {
    messageList.value.push({
        messageType: '',
        userId: '',
        messageId: '',
        operationType: '',
        facilitator: '',
        dataAuthType: ''
    })
}
// 获取消息通知设置
function getMessageSet() {
    messageList.value.forEach((item => {
        if (!templateList.value[item.messageType]) {
            changeMessageType(item, false)
        }
    }))
}
function getMessageList() {
    return messageList.value
}
function setRoleList(valArr) {
    roleList.value = []
    let userInfo = getStore({ name: 'userInfo' })
    let isHaveOwn = false, userIdList = []
    valArr.forEach((item, index) => {
        if (item.id == userInfo.id) {
            isHaveOwn = true
        }
        if (userIdList.indexOf(item.id) == -1) {
            roleList.value.push(item)
            userIdList.push(item.id)
        }
    })
    if (!isHaveOwn) {
        roleList.value.splice(0, 0, {
            id: userInfo.id,
            type: 'user',
            name: userInfo.realName
        })
    }
}
function changeMessageType(item, isReset = true) {
    if (isReset) {
        item.messageId = ''
    }
    let fun = null
    switch (item.messageType) {
        case 'inside':
            fun = messageInsideSelect
            break;
        case 'email':
            fun = messageEmailSelect
            break;
        case 'sms':
            fun = messageSmsSelect
            break;
        default:
            fun = messageWxSelect
            break;
    }
    if (fun) {
        fun().then(res => {
            if (res.data.code == 0) {
                templateList.value[item.messageType] = res.data.data || []
            }
        })
    }
}
function delMessage(index) {
    messageList.value.splice(index, 1)
}
function getCurrentTemplateList(val) {
    return templateList.value[val] || []
}
function roleChange(val, index) {
    roleList.value.forEach((item) => {
        if (item.id == val) {
            messageList.value[index].dataAuthType = item.type
        }
    })
}
defineExpose({
    init,
    setRoleList,
    getMessageSet,
    getMessageList
})
</script>
<style lang="scss" scoped>
.sticky-box {
    position: sticky;
    top: 0px;
    background: #fff;
    z-index: 3;
    padding-top: 16px;

    .title-tips {
        margin-top: 0px !important;
    }

    .item-title {
        margin-bottom: 0px !important;
        padding-bottom: 8px;

        .title {
            font-size: 14px;
            @include SourceHanSansCN-Bold;
        }
    }
}

.message-lists {
    display: grid;
    grid-row-gap: 16px;

    .message-list-item {
        display: flex;
        align-items: center;
        grid-column-gap: 13px;

        .item-action {
            .del-icon {
                height: 14px;
                width: 14px;
                cursor: pointer;
            }
        }

        .el-select {
            ::v-deep(.select-trigger) {
                input {
                    font-size: 12px !important;
                }

                input::-webkit-input-placeholder {
                    color: #6f7588;
                    @include SourceHanSansCN-Regular;
                }

                .el-input {
                    .el-input__wrapper {
                        padding: 0px 8px !important;

                        .el-input__suffix {
                            i {
                                margin-left: 0px !important;
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>